package com.nuanshui.heatedloan.baseservice.service;

import com.nuanshui.framework.lang.SysStringUtils;
import com.nuanshui.framework.res.ResourceFacade;
import com.nuanshui.framework.res.UploadRequest;
import com.nuanshui.framework.res.qiniu.*;
import com.nuanshui.framework.res.qiniu.impl.QiniuBeanManager;
import com.nuanshui.framework.security.MD5Util;
import com.nuanshui.framework.utils.FlagOperationFactory;
import com.nuanshui.heatedloan.baseservice.facade.ImageService;
import com.nuanshui.heatedloan.enums.FileBelong;
import com.nuanshui.heatedloan.model.Image;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.util.regex.Pattern;


/**
 * 非线上环境的资源门面
 * 
 * @author jamesp
 */
public class ResourceFacadeNonProdImpl implements ResourceFacade {

	//@Autowired
	private ImageService imageService;

	public void setImageService(ImageService imageService)
	{
		this.imageService=imageService;
	}

	public ImageService getImageService()
	{
		return imageService;
	}

	@Autowired
	private Qiniu qiniu;

	@Autowired
	private QiniuBeanManager qiniuBeanManager;

	@Value("${site.web.host.name}")
	String siteHost;

	@Value("${qiniu.extfmt}")
	String qiniuExtFmt;

	static final String RES_PREFIX_SYS = "/_resources";

	/**
	 * 根据给定的key值返回图片地址
	 *
	 * @param
	 * @author guohao
	 * @date 2015年4月14日 下午5:41:22
	 */
	@Override
	public String resolveUrl(String resKey) {
		return resolveUrl(resKey,false);
	}

	@Override
	public String resolveUrl(String resKey, boolean isContainArg) {
		return resolveUrl(resKey,null,isContainArg);
	}

	/**
	 * 根据 图片key和 宽度得到图片的全路径
	 *
	 * @param
	 * @author guohao
	 * @date 2015年4月21日 上午11:51:14
	 */
	@Override
	public String resolveUrl(String resKey, Integer width) {
		return resolveUrl(resKey,width,null);
	}

	public String resolveUrl(String resKey, Integer width,Boolean isContainArg) {
		if (SysStringUtils.isBlank(resKey)) {
			return genQiniuFileUrl("qn|xunbaozl|default_avatar.png", width);
		} else if (resKey.startsWith(EXT_RES_PREFIX)) {
			return resKey;
		} else if (resKey.startsWith(RES_PREFIX_SYS)) {
			return siteHost + resKey;
		} else if (resKey.startsWith(FILE_STORE_KEY_V2)) {
			if(width!=null)
			{
				return genQiniuFileUrl(resKey, width);// 返回七牛的URL，直接去七牛服务器上取
			}
			if(isContainArg!=null)
			{
				return genQiniuFileUrl(resKey,isContainArg);
			}
			return genQiniuFileUrl(resKey);// 返回七牛的URL，直接去七牛服务器上取
		}
		return siteHost + RES_PREFIX_UP_FILE + (resKey.startsWith("/") ? "" : "/") + resKey;
	}

	@Override
	public String genUpTokenForClient(FileBelong belong) throws Exception {
		return qiniu.genUpTokenForClient(qiniu.genBucketName(belong));
	}

	@Override
	public String resolveUrl(String resKey, int x, int y, int width, int height) {
		String url = this.resolveUrl(resKey, false);
		StringBuilder sb = new StringBuilder(url);
		sb.append("?imageMogr2/crop/!{0}x{1}a{2}a{3}");
		sb.append(x);
		sb.append("x");
		sb.append(y);
		sb.append("a");
		sb.append(width);
		sb.append("a");
		sb.append(height);
		return sb.toString();
	}

	public UpLoadFileResult uploadFile(UploadRequest request)
	{
		UpLoadFileResult fileResult= null;
		try {
			fileResult = qiniu.uploadFile(request);
			fileResult.getFile().setUrl(resolveUrl(fileResult.getFile().getKey(),false));
		} catch (Exception e) {
			e.printStackTrace();
		}

		boolean bMd5= FlagOperationFactory.getResultOp().containFlag(request.getRequestFlag(), UploadOptionFlag.OPTION_MD5);
		if(bMd5)
		{
			fileResult.getFile().setMd5Code(MD5Util.getMd5ByInputStream(request.getInputStream()));
		}

		boolean bSaved= FlagOperationFactory.getResultOp().containFlag(request.getRequestFlag(), UploadOptionFlag.OPTION_SAVE);
		if(bSaved)
		{
			this.saveToLocal(fileResult);
		}
		return fileResult;
	}

	protected void saveToLocal(UpLoadFileResult fileResult) {

		if(imageService==null)
			return;
		Image image = imageService.loadByImgKey(fileResult.getFile().getKey());
		if (image != null) {
			fileResult.setImage(image);
			return;
		}

		String imageId=imageService.insert(fileResult.getImage());

		fileResult.getImage().setId(imageId);
	}

	/**
	 * 根据本地数据库中保存的key，转换成图片url
	 */

	public String genQiniuFileUrl(String localKey) {
		return genQiniuFileUrl(localKey, true);
	}

	/**
	 * 根据本地数据库中保存的key，转换成图片url
	 */
	public String genQiniuFileUrl(String localKey, boolean isContainArg) {
		String[] keys = localKey.split("\\|");
		if (keys.length < 3) {
			return "";
		}

		String bucketName = keys[1];
		String qiniuKey = keys[2];
		QiniuBean bean = qiniuBeanManager.findQiniuBeanByBucketName(bucketName);
		if (bean == null) return "";
		if (isContainArg) {
			String style = convert2QiniuStyle(keys.length > 3 ? keys[3] : "", 480, isContainArg);
			return bean.siteHost + "/" + qiniuKey + style;
		} else {
			return bean.siteHost + "/" + qiniuKey;
		}

	}

	public String genQiniuFileUrl(String localKey, Integer width) {
		String[] keys = localKey.split("\\|");
		if (keys.length < 3) {
			return "";
		}

		String bucketName = keys[1];
		String qiniuKey = keys[2];
//        String wh = keys[3];
		QiniuBean bean = qiniuBeanManager.findQiniuBeanByBucketName(bucketName);
		if (bean == null)
			return "";

		if (!"resource".equals(bean.bucketType)) {
//            Integer w = Integer.parseInt(wh.substring(0, wh.indexOf('x')));
//            if (width == null || width > w || width <= 0) {
//                width = w;
//            }
			if (width == null) {
				width = 480;
			}

			String style = convert2QiniuStyle(keys.length > 3 ? keys[3] : "", width, false);
			return bean.siteHost + "/" + qiniuKey + style;
		} else {
			return bean.siteHost + "/" + qiniuKey;
		}
	}

	protected String convert2QiniuStyle(String localStyle, Integer maxWidth, boolean isContainArg) {
		String qiuiuStyle = null;
		//maxWidth = 480;
		// 大括号包围的表示
		if (Pattern.matches("\\{(.+?)\\}", localStyle)) {
			JSONObject jsonObj;
			try {
				jsonObj = new JSONObject(localStyle);
				int width = jsonObj.optInt("w", maxWidth);
				int height = jsonObj.optInt("h", 0);
				int quality = jsonObj.optInt("q", 90);
				int mode = jsonObj.optString("m", "cut").equals("cut") ? 1 : 2;
				qiuiuStyle = "?imageView2/" + mode + "/w/" + width + "/q/" + quality;
				if (height > 0)
					qiuiuStyle += "/h/" + height;
				if (isContainArg) {
					qiuiuStyle += qiniuExtFmt;
				}
			} catch (JSONException e) {
				//  throw new BizException(GlobalErrorCode.INVALID_ARGUMENT, "图片参数错误");
			}

		} else { //支持老的方式
			if (ResourceFacade.IMAGE_S1.equals(localStyle)) {
				qiuiuStyle = "?imageView2/2/w/" + maxWidth;
			} else if (ResourceFacade.IMAGE_S03.equals(localStyle)) {
				qiuiuStyle = "?imageView2/2/w/" + (int) (maxWidth * 0.3);
			} else if (ResourceFacade.IMAGE_S05.equals(localStyle)) {
				qiuiuStyle = "?imageView2/2/w/" + (int) (maxWidth * 0.5);
			} else if (ResourceFacade.IMAGE_S025.equals(localStyle)) {
				qiuiuStyle = "?imageView2/2/w/" + (int) (maxWidth * 0.25);
			} else {
				qiuiuStyle = "?imageView2/2/w/" + maxWidth;
			}
			if (isContainArg) {
				qiuiuStyle += "/q/90" + qiniuExtFmt;
			} else {
				qiuiuStyle += "/q/90";
			}
		}
		return qiuiuStyle;
	}
}
